package org.erp.store.infrastructure.listener;

import lombok.extern.log4j.Log4j2;
import org.erp.store.domain.entity.DeviceInventory;
import org.erp.store.infrastructure.convert.DeviceInventoryConvert;
import org.erp.store.infrastructure.event.ProductCallbackEvent;
import org.erp.store.infrastructure.remote.ProductRemoteClient;
import org.erp.store.domain.dto.DeviceInventoryRemoteDto;

import org.erp.store.domain.dto.BatchDeviceInventoryDto;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;
import java.util.List;

@Log4j2
@Component
public class ProductCallbackEventListener {

    @Resource
    private ProductRemoteClient productRemoteClient;

    @Resource
    private DeviceInventoryConvert deviceInventoryConvert;

    @Async("productCallbackExecutor")
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void handle(ProductCallbackEvent event) {
        try {
            DeviceInventoryRemoteDto dto = buildRemoteDto(event.getDto(),event.getInventoryList());
            String ret = productRemoteClient.productCallback(dto);
            log.info("产品回调成功，事件：{}，返回：{}", dto.getTargetEvent().getMessage(), ret);
        } catch (Exception ex) {
            log.error("产品回调失败，错误：{}", ex.getMessage(), ex);
        }
    }


     private DeviceInventoryRemoteDto buildRemoteDto(BatchDeviceInventoryDto messageDto, List<DeviceInventory> list) {
        DeviceInventoryRemoteDto dto = new DeviceInventoryRemoteDto();
        dto.setOperationId(messageDto.getOperateId());
        dto.setOperationName(messageDto.getOperateName());
        dto.setTransferId(messageDto.getTransferUserId());
        dto.setTransferName(messageDto.getTransferUserName());
        dto.setTargetEvent(messageDto.getTargetEvent());
        dto.setConnectLogAddBoList(deviceInventoryConvert.ToProductRemoteDto(list));
        dto.setBatchId(messageDto.getBatchId());
        return dto;
    }
}
